<?php
/**
 * Classe responsável por fazer upload
 * @package    GraduaUtil
 * @subpackage upload
 * @author     Original Author helber fernandes <helber.gradua@gmail.com>
 */
class GraduaUpload
{

    /**
     * Função utilizada para fazer upload
     *
     * @param sfWebRequest $request Recebe o objeto do tipo request
     * @param string       $fileName   O nome do arquivo. (campo do form)
     * @param string       $uploadDir  O diretório de destino. Se for nulo, é utilizado o padrão do Symfony
     * @param string       $fileRename O nome do arquivo que será utilizado ao mover o arquivo enviado
     *                                 para o diretório de destino. Forneça somente o nome, sem a extensão.
     * @param string       $type O mime type permitido para o arquivo. Se não for especificado, aceita qualquer um.
     * @return string O arquivo que foi feito upload
     */
    public static function doUploadFile($fieldName,
                                        sfWebRequest $request,
                                        $uploadDir = null,
                                        $fileRename = null,
                                        $arType=array( 0 => "application/msword",
                                                       1 => "application/pdf",
                                                       2 => "application/vnd.ms-powerpoint",
                                                       3 => "application/vnd.ms-powerpoint",
                                                       4 => "image/jpeg",
                                                       5 => "image/gif",
                                                       6 => "text/plain",
                                                       7 => "image/bmp",
                                                       8 => "image/png",
                                                       9 => "image/ex-png",
                                                      10 => "application/rtf",
                                                      11 => "application/x-rtf",
                                                      12 => "application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
                                        {

        if (!$request->hasFiles()) {
            throw new FileNotRequestException('File was not send.');
        }

        $fieldName     = $fieldName;
        $uploadDir     = $uploadDir ? $uploadDir : sfConfig::get('sf_upload_dir');// Setando o destino
        $fileName      = $request->getFileName($fieldName);// Setando o nome do arquivo

        $info = pathinfo($fileName);
        $fileExtension = $info['extension'];

        $fileError     = $request->hasFileError($fieldName);
        if (null !== $fileRename) {
            $fileName = $fileRename . '.' . ltrim($fileExtension, '.');
        }
        /// throw new UploadException('Invalid file type. Supported types are: '.$fileName );
        // Outras informações do arquivo
        $fileSize  = $request->getFileSize($fieldName);
        $fileType  = $request->getFileType($fieldName);

        if (!in_array($request->getFileType($fieldName),$arType)) {
            throw new UploadInvalidTypeException('Invalid File Type', 0,
                sprintf( GeneralMessages::INVALID_FILE_TYPE, $request->getFileType($fieldName), implode(',',$arType))
            );
        }

        // Movendo
        $request->moveFile($fieldName, $uploadDir. DIRECTORY_SEPARATOR . $fileName);

        if (!empty($fileError)) {
            switch ($fileError) {
                case '0':  throw new UploadException('The uploaded file with success!!');
                case '1':  throw new UploadException('The uploaded file exceeds the upload_max_filesize directive in php.ini');
                case '2':  throw new UploadException('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form');
                case '3':  throw new UploadException('The uploaded file was only partially uploaded');
                case '4':  throw new UploadException('No file was uploaded.');
                case '5':  throw new UploadException( );
                case '6':  throw new UploadException('Missing a temporary folder');
                case '7':  throw new UploadException('Failed to write file to disk');
                case '8':  throw new UploadException('File upload stopped by extension');
                case '999':
                default:  throw new UploadException('No error code available');
            } // switch
        } //

        return $fileName;
    }
}
?>